<!-- 
 * Copyright (c) 2021-2025 申菱环境 All Rights Reserved
 * 项目名称：申菱物联平台
 * 模块名称：服务申请
 * 功能名称：申请首页
 * author : huzhiqi
 * date   : 2022/7/14 10:20
 -->
<template>
  <TablePage>
    <template #top>
      <div class="font-semibold text-2xl pb-1 text-color-header">
        {{ t("routes.serviceApply") }}
      </div>
      <!-- <SearchForm :title="t('routes.serviceApply')" :show-add-btn="false" @search="handleSearch" /> -->
      <a-tabs v-model:activeKey="activeKey" class="sl-tabs">
        <a-tab-pane key="ALL" style="height: 0px">
          <template #tab>
            <div class="flex flex-row items-center">
              <div class="mr-1.5">
                <a-badge
                  :count="applyNum?.serviceOrdersTotal"
                  show-zero
                  :number-style="{
                    backgroundColor: '#4285F4',
                    color: '#fff',
                    boxShadow: '0 0 0 1px #4285F4 inset',
                    width: '40px',
                    height: '24px',
                    lineHeight: '24px',
                    fontSize: '14px',
                  }"
                ></a-badge>
              </div>
              <div class="text-lg"> {{ t("aiot.serviceApply.tabAll") }} </div>
            </div>
          </template>
        </a-tab-pane>
        <a-tab-pane key="CREATE">
          <template #tab>
            <div class="flex flex-row items-center">
              <div class="mr-1.5">
                <a-badge
                  :count="applyNum?.serviceOrdersCreating"
                  show-zero
                  :number-style="{
                    backgroundColor: 'rgba(253,131,88,0.10)',
                    color: '#FD8358',
                    boxShadow: '0 0 0 1px #FD8358 inset',
                    width: '40px',
                    height: '24px',
                    lineHeight: '24px',
                    fontSize: '14px',
                  }"
                ></a-badge>
              </div>
              <div class="text-lg"> {{ t("aiot.serviceApply.tabCreate") }} </div>
            </div>
          </template>
        </a-tab-pane>
        <a-tab-pane key="CREATED">
          <template #tab>
            <div class="flex flex-row items-center">
              <div class="mr-1.5">
                <a-badge
                  :count="applyNum?.serviceOrdersCreated"
                  show-zero
                  :number-style="{
                    backgroundColor: 'rgba(56,206,123,0.10)',
                    color: '#38CE7B',
                    boxShadow: '0 0 0 1px #38CE7B inset',
                    width: '40px',
                    height: '24px',
                    lineHeight: '24px',
                    fontSize: '14px',
                  }"
                ></a-badge>
              </div>
              <div class="text-lg"> {{ t("aiot.serviceApply.tabCreated") }} </div>
            </div>
          </template>
        </a-tab-pane>
        <a-tab-pane key="CANCLE">
          <template #tab>
            <div class="flex flex-row items-center">
              <div class="mr-1.5">
                <a-badge
                  :count="applyNum?.serviceOrdersCancle"
                  show-zero
                  :number-style="{
                    backgroundColor: ' rgba(123,135,154,0.10)',
                    color: '#7B879A',
                    boxShadow: '0 0 0 1px #7B879A inset',
                    width: '40px',
                    height: '24px',
                    lineHeight: '24px',
                    fontSize: '14px',
                  }"
                ></a-badge>
              </div>
              <div class="text-lg"> {{ t("aiot.serviceApply.tabCancel") }} </div>
            </div>
          </template>
        </a-tab-pane>
      </a-tabs>
      <SearchForm
        v-model:keyword="keyword"
        :keyword-search-data="searchModel"
        :select-data="selectData"
        :show-add-btn="false"
        @search="handleSearch"
      />
    </template>
    <SlTable
      :columns="columns"
      row-key="serviceOrderId"
      :data-source="tableData"
      :loading="tableLoading"
      :pagination="pagination"
      :scroll="{ x: 'auto' }"
      :search-model="applySearchModel"
      @change="handleTableChange"
    >
      <template #bodyCell="{ column, record }">
        <a-space v-if="column.key === 'oper'">
          <PermissionBtn
            v-if="record.serviceState === 'WAITING'"
            :btn-props="{ type: 'link' }"
            :oper-type="OperPermissionType.MANAGE"
            @click="createWorkOrderFn(record)"
            >{{ t("aiot.serviceApply.addWorkOrder") }}</PermissionBtn
          >
          <PermissionBtn
            v-if="record.serviceState === 'WAITING'"
            :btn-props="{ type: 'link' }"
            :oper-type="OperPermissionType.MANAGE"
            @click="handleCancelFn(record)"
            >{{ t("common.cancel") }}</PermissionBtn
          >
          <!-- <PermissionBtn
            v-if="record.serviceState === 'WAITING'"
            :btn-props="{ type: 'link', danger: true }"
            :oper-type="OperPermissionType.MANAGE"
            @click="handleRevokeFn(record)"
            >{{ t("aiot.serviceApply.revoke") }}</PermissionBtn
          > -->
          <!-- <PermissionBtn
            v-if="record.serviceState !== 'WAITING' && record.serviceState !== 'CANCEL'"
            :btn-props="{ type: 'link' }"
            :oper-type="OperPermissionType.MANAGE"
            @click="dispatchWorkOrderFn(record)"
            >{{ t("aiot.serviceApply.dispatchWorkOrder") }}</PermissionBtn
          > -->
        </a-space>
        <div v-if="column.dataIndex === 'serviceState'">
          <!-- <a-tag class="sl-tag !mr-2 !mb-2" :color="serviceStateColor[record.serviceState]">
            {{ record.serviceStateName }}
          </a-tag> -->
          <StateTag
            :color="record.serviceStateName === '超期' ? '#f5b83c' : serviceStateColor[record.serviceState || '']"
            :value="record.serviceStateName"
          ></StateTag>
        </div>
        <div v-if="column.dataIndex === 'serviceType'">
          {{ getLabelByValueFromEnum(record.serviceType, ServiceType, "serviceType") }}
        </div>
        <EllipsisText v-if="column.dataIndex === 'address'" :max-len="10" :text="record.address" />
        <a
          v-else-if="column.dataIndex === 'serviceOrderCode'"
          href="javascript:void(0)"
          @click="handleViewDetailFn(record)"
        >
          {{ record.serviceOrderCode }}
        </a>
        <div v-if="column.dataIndex === 'contactsPerson'">
          {{ record.contactsPerson + "(" + record.contactsPhone + ")" }}
        </div>
      </template>
    </SlTable>
    <CreateModal
      v-model:visible="createVisible"
      :service-order-id="serviceOrderId"
      @create="reloadTable"
      @ok="handleSuccessFn"
    />
    <DispatchWorkOrder
      v-model:visible="dispatchModal"
      v-model:serviceOrderId="currentServiceApply.serviceOrderId"
      :current-btn-type="BtnType.DISPATCH"
      :model="dispatchModel"
      :model-form-setting="dispatchModelFormSetting"
      @create="reloadTable"
    />
    <CancelApplyModal v-model:visible="cancelOrderVisible" :options="cancelModalOptions" @ok="refresh" />

    <SelectUserModal
      v-model:visible="chooseUserVisible"
      v-model:projectId="currentServiceApply.projectId"
      v-model:selectMode="selectUserMode"
      :selected-user-ids="selectedUserIds"
      @ok="handleSelectedUser"
    />
    <ServiceApplyDetails
      v-model:visible="detailVisible"
      v-model:serviceOrderId="currentServiceApply.serviceOrderId"
      @cancel-fn="handleCancelFn"
      @create-fn="createWorkOrderFn"
    />
  </TablePage>
</template>
<script lang="ts" setup>
import DispatchWorkOrder from "/@/components/DispatchWorkOrder.vue";
import ServiceApplyDetails from "./ServiceApplyDetails.vue";
import SelectUserModal from "/@/components/SelectUserModal.vue";
import TablePage from "/@/components/TablePage.vue";
import { ref, onMounted, watch } from "vue";
import { useI18n } from "/@/locales/useI18n";
import { Api, revokeServiceOrder, summaryServiceOrders } from "/@/api/aiot/serviceApply";
import { BtnType, StateColorList } from "/@/api/aiot/serviceWorkOrder/models";
import {
  ServiceOrderItem,
  ServiceStateMapper,
  StateColor,
  WorkOrderItem,
  ServiceType,
} from "/@/api/aiot/serviceApply/models";
import SearchForm from "/@/components/SearchForm.vue";
import { useCURD } from "/@/hooks/useCURD";
import { enumToOptions, getLabelByValueFromEnum } from "/@/utils/common";
import { OperPermissionType } from "/@/api/aiot/role/models";
import PermissionBtn from "/@/components/PermissionBtn.vue";
import { CURDAction, OperItem, ShowCURDModalOptions } from "/@/components/CURDDialog/models";
import { PatternKey } from "/@/utils/verify";
import SlTable from "/@/components/SlTable.vue";
import { OrderRule } from "/@/api/models";
import { useServiceApplyModal } from "./useServiceApplyModal";
import { ApplyNumItem } from "/@/api/aiot/serviceApply/models";
import CreateModal from "./CreateModal.vue";
import InfoModal from "../../InfoModal";
import { message } from "ant-design-vue";
import { cancelServiceOrder } from "/@/api/aiot/serviceWorkOrder";
import { CancelApplyModalOptions } from "/@/types/components";
import { LabelSelectType, SelectItem } from "../../../types/components";

const { t } = useI18n();
const {
  selectUserMode,
  columns,
  dispatchModel,
  dispatchModelFormSetting,
  chooseUserVisible,
  // selectData,
  handleSelectedUser,
} = useServiceApplyModal();
const selectData = ref<SelectItem[]>([
  {
    label: t("aiot.serviceApply.serviceType"),
    value: "",
    key: "serviceType",
    options: enumToOptions(ServiceType, "serviceType"),
  },
  {
    label: t("aiot.applyManage.applicantOn"),
    value: "",
    props: { allowClear: true },
    key: "expectedTime",
    selectType: LabelSelectType.rangePicker,
  },
]);
selectData.value[0].options?.unshift({ label: "全部", value: "" });
const cancelModalOptions = ref<CancelApplyModalOptions>();
const activeKey = ref<string>("ALL");
const keyword = ref<string>("");
const createVisible = ref<boolean>(false);
const dispatchModal = ref<boolean>(false);
const cancelOrderVisible = ref<boolean>(false);
const currentServiceApply = ref<ServiceOrderItem>({});
const selectedUserIds = ref<Array<string>>([]);
const serviceStateColor = {
  WAITING: "#f56d6a",
  SERVICE: "#38ce7b",
  CREATED: "#38ce7b",
  EVALUATED: "#38ce7b",
  FINISHED: "#38ce7b",
  RECEIVED: "#38ce7b",
  CANCEL: "#7b879a",
};
watch(activeKey, (val) => {
  let model = {
    serviceState: val,
    searchText: keyword.value,
  };
  // reloadTable({ model: { serviceState: val }, current: 1, sort: "createdOn", order: OrderRule.ASC });
  reloadTable({ model, current: 1, sort: "createdOn", order: OrderRule.DESC });
});
const showOptions = ref<ShowCURDModalOptions>();
const serviceOrderId = ref<string>("");
const detailVisible = ref<boolean>(false);
const applyNum = ref<ApplyNumItem | null>({});
function handleSuccessFn() {
  createVisible.value = false;
  message.success(t("aiot.serviceOrderOperationMsg.createOrderMsg"));
  refresh();
}
function refresh() {
  reloadTable();
  getSummary();
  detailVisible.value = false;
}
onMounted(async () => {
  reloadTable({ current: 1, sort: "createdOn", order: OrderRule.DESC });
  getSummary();
});
function handleTableChange(pag: { pageSize: number; current: number }, filters: any, sorter: any) {
  if (sorter.field === "createdOn") {
    let obj = { sort: "createdOn", order: OrderRule.ASC };
    if (sorter.order === "ascend") {
      obj.order = OrderRule.ASC;
    } else if (sorter.order === "descend") {
      obj.order = OrderRule.DESC;
    } else {
      obj.order = OrderRule.DESC;
    }
    reloadTable(obj);
  }
}
async function getSummary() {
  let req = await summaryServiceOrders();
  applyNum.value = req;
}
function handleViewDetailFn(record) {
  currentServiceApply.value = record;
  detailVisible.value = true;
}
// 派单
function dispatchWorkOrderFn(record) {
  currentServiceApply.value = record;
  dispatchModal.value = true;
}
/**
 * 取消工单
 * @param record
 */
function handleCancelFn(record) {
  cancelOrderVisible.value = true;
  cancelModalOptions.value = {
    serviceOrderId: record.serviceOrderId,
  };
}
/**
 * 撤销工单
 */
async function handleRevokeFn(record: WorkOrderItem) {
  InfoModal.confirm({
    content: t("aiot.serviceApply.revokeMsg"),
    async onOk() {
      let req = await revokeServiceOrder({ serviceOrderId: record.serviceOrderId || "" });
      if (req) {
        message.success(t("aiot.serviceApply.revokeSuccess"));
        refresh();
      }
    },
  });
}
// 服务单号/项目/设备名
const searchModel = [{ key: "searchText", label: t("aiot.serviceOrderOperationMsg.searchTextServiceApply") }];
function handleSearch(model) {
  if (model?.expectedTime?.length > 0) {
    model.createdOnStart = model.expectedTime[0];
    model.createdOnEnd = model.expectedTime[1];
  } else {
    model.createdOnStart = "";
    model.createdOnEnd = "";
  }
  model.serviceType === "ALL" ? (model.serviceType = "") : null;
  reloadTable({ model, current: 1, sort: "createdOn", order: OrderRule.DESC });
}
const {
  tableData,
  tableLoading,
  curd,
  reloadTable,
  pagination,
  searchModel: applySearchModel,
} = useCURD<ServiceOrderItem>({
  getPageUrl: Api.getApplyPage,
  loadOnMounted: false,
});
// 服务状态 服务状态 ALL,CREATE,CREATED,CANCLE,可用值:ALL,CREATE,CREATED,CANCLE
const operData: OperItem<ServiceOrderItem>[] = [
  {
    label: t("common.edit"),
    handler: showUpdateModal,
  },
  {
    label: t("common.delete"),
    type: "primary",
    danger: true,
    handler: deleteRecord,
  },
];
function createWorkOrderFn(record) {
  serviceOrderId.value = record.serviceOrderId;
  createVisible.value = true;
}
function showUpdateModal(record) {
  showOptions.value = { action: CURDAction.UPDATE, record };
}
function deleteRecord(record) {
  showOptions.value = { action: CURDAction.DELETE, record };
}
</script>
<style lang="less" scoped>
// :deep(.ant-tabs-tab-btn) {
//   display: flex;
// }
// :deep(.ant-tabs-tab-btn span) {
//   font-size: 16px !important;
// }
// :deep(.ant-tabs-tab-btn) {
//   display: flex;
//   flex-direction: row;
//   align-items: center;
// }
</style>
